package com.jt.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 定义服务消费端Controller，在这个Controller对象
 * 的方法中实现对远程端服务sca-provider的调用
 */
@RestController
public class ConsumerController {
    @Value("${spring.application.name}")
    private String name;
    /**
     * 从Spring容器中获取一个RestTemplate对象
     * 基于此对象实现远端服务的调用
     */
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 在此方法中通过一个对象调用远端sca-provider中的服务
     * @return
     */
    @GetMapping("/consumer/doRestEcho01")
    public String doRestEcho01(){
        //1.定义要调用的远端服务的url
        //2.基于RestTemplate对象中的相关方式进行服务调用
        String url = "http://localhost:8081/provider/echo/"+name;

        return restTemplate.getForObject(url, String.class );
    }


//负责从nacos服务中发现和获取服务实例
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/consumer/doRestEcho02")
    public String doRestEcho02(){
        //1.获取服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),name);
        System.out.println("request url:"+url);
        return restTemplate.getForObject(url, String.class);
    }

    /**
     *
     */
    @Autowired
    private RestTemplate lod;
    @GetMapping("/consumer/doRestEcho03")
    public String doRestEcho03(){
    String url = "http://sca-provider/provider/echo/"+name;
        return lod.getForObject(url,String.class);
    }
}


